hojo.provide("icallcenter.callProcessor");
hojo.require("hojo.io.script");

function aaa() {

	console.info("222222==================")
}

hojo.declare("icallcenter.callProcessor", null, {
	_phone: null,

	constructor: function (phone) {
		this._phone = phone;
		var evtHandle = this._phone.register("EvtRing", this, "onRing");
		this._phone._handles.push(evtHandle);
		var evtHandle = this._phone.register("EvtHangup", this, "onHangup");
		this._phone._handles.push(evtHandle);
		evtHandle = this._phone.register("EvtDialing", this, "onDialing");
		this._phone._handles.push(evtHandle);
		evtHandle = this._phone.register("EvtPeerStatusChanged", this, "peerStatusChanged");
		this._phone._handles.push(evtHandle);
		evtHandle = this._phone.register("EvtCallStatusChanged", this, "callStatusChanged");
		this._phone._handles.push(evtHandle);
		evtHandle = this._phone.register("EvtConnected", this, "EvtConnected");
		this._phone._handles.push(evtHandle);
		evtHandle = this._phone.register("EvtLogon", this, "EvtLogon");
		this._phone._handles.push(evtHandle);
		evtHandle = this._phone.register("EvtMonitorQueue", this, "EvtMonitorQueue");
		this._phone._handles.push(evtHandle);
	},
	onRing: function (data) {

		//debugger
		console.info("onRing==================")
		//alert("tpblcs===="+data.data.tpblcs);
		console.dir(data)

		var callsheetId = data.callSheetId; //来电振铃
		var agent = data.agent; //坐席
		var callNo = data.originCallNo;//主叫
		var calledNo = data.originCalledNo;//被叫
		var callType = data.callType;
		var status = data.status;
		var ringTime = data.offeringTime;
		var beginTime = "";
		var endTime = "";
		var monitorFilename = "";
		hojo.byId("icallcenter.dialout.input").value = callNo;
		var str = "";
		if (data.callerProvince && data.callerCity) {
			str += "来电归属地：" + data.callerProvince + "   " + data.callerCity;
		}
		if (data.callType == 'transfer') {
			str += "转接来电来自座席：" + data.data.Agent;
		}
		hojo.byId("memo_info_div").innerHTML = str;

	},

	onHangup: function (data) {
		//挂断
		//alert("测试挂断弹出");
		hojo.byId("memo_info_div").innerHTML = "";
		console.info("onHangup=============")
		console.log(data);
		var callsheetId = data.callSheetId;
		var agent = data.agent;
		var callNo = data.originCallNo;
		var calledNo = data.originCalledNo;
		var callType = data.callType;
		var status = data.status;
		var ringTime = data.ringTime;
		var beginTime = data.beginTime;
		var endTime = data.endTime;
		var monitorFilename = data.data.MonitorFilename;
		////alert("agent:" + agent +";callNo:" + callNo+";calledNo:"+calledNo+";callType:"+callType+";status:"+status+";ringTime:"+ringTime+";beginTime:"+beginTime+";endTime:"+endTime+";monitorFilename:"+monitorFilename);
		var phoneJson = {
			Command: "Action",
			Action: "Hangup",
			ActionID: "Hangup" + Math.random(),
			CallsheetId: callsheetId,
			CallNo: callNo,
			CalledNo: calledNo,
			CallType: callType,
			RingTime: ringTime,
			Agent: agent,
			Status: status,
			BeginTime: beginTime,
			EndTime: endTime,
			MonitorFilename: monitorFilename
		};
		this.sendAction(phoneJson);
	},

	onDialing: function (data) {//外呼时坐席响铃触发
		//debugger
		console.info("onDialing======================")
		console.log(data);

		var callsheetId = data.callSheetId;
		var agent = "";
		var callNo = data.originCallNo;
		var calledNo = data.originCalledNo;
		var callType = data.callType;
		var status = data.status;
		var ringTime = data.offeringTime;
		var beginTime = "";
		var endTime = "";
		var monitorFilename = "";
		var phoneJson = {
			Command: "Action",
			Action: "Dialing",
			ActionID: "Dialing" + Math.random(),
			CallsheetId: callsheetId,
			CallNo: callNo,
			CalledNo: calledNo,
			CallType: callType,
			RingTime: ringTime,
			Agent: agent,
			Status: status,
			BeginTime: beginTime,
			EndTime: endTime,
			MonitorFilename: monitorFilename
		};
		this.sendAction(phoneJson);
	},

	EvtConnected: function (data) {//接听触发

		console.info("EvtConnected======================")
		var callsheetId = data.callSheetId;
		var agent = "";
		var callNo = data.originCallNo;//
		var calledNo = data.originCalledNo;//
		var callType = data.callType;
		var status = data.status;
		var ringTime = data.offeringTime;
		var beginTime = data.beginTime;
		var endTime = "";
		var monitorFilename = "";
		var phoneJson = {
			Command: "Action",
			Action: "Connected",
			ActionID: "Connected" + Math.random(),
			CallsheetId: callsheetId,
			CallNo: callNo,
			CalledNo: calledNo,
			CallType: callType,
			RingTime: ringTime,
			Agent: agent,
			Status: status,
			BeginTime: beginTime,
			EndTime: endTime,
			MonitorFilename: monitorFilename
		};
		this.sendAction(phoneJson);
	},

	EvtLogon: function (data) { //登入会触发
		var status = data;
		var phoneJson = {
			Command: "Action",
			Action: "Logon",
			ActionID: "Logon" + Math.random(),
			Status: status
		};
		this.sendAction(phoneJson);
	},
	//下面聊天是状态改变（坐席状态转化，通话事件）
	peerStatusChanged: function (data) {
		//    	var peerStatus = data; 
		//	   	var phoneJson = {
		//	    		Command: "Action",
		//	    		Action: "Peer",
		//	    		ActionID: "Peer" + Math.random(),
		//	    		Status: peerStatus
		//		};
		//	   	this.sendAction(phoneJson);
	},

	callStatusChanged: function (data) {
		//    	var peerStatus = data; 
		//	   	var phoneJson = {
		//	    		Command: "Action",
		//	    		Action: "Call",
		//	    		ActionID: "Call" + Math.random(),
		//	    		Status: peerStatus
		//		};
		//	   	this.sendAction(phoneJson);
	},

	EvtMonitorQueue: function (queueItem) {
		console.info("EvtMonitorQueue--");

		try {
			console.log(this.oQueueItem);
			console.log(queueItem);


			if (this.oQueueItem == null || this.oQueueItem == undefined || this.oQueueItem == '') {
				this.oQueueItem = '1498627266000#';
			}

			var oQueueItemt = '';
			var timestampO = this.oQueueItem.split('#')[0];
			console.log("队列数据历史时间：" + timestampO);

			var tQueueItem = [];

			tQueueItem = this.oQueueItem.split('#')[1].split('&');

			var isFlag = -1; // -1不存在 0存在&相同 1存在&不相同
			tQueueItem.forEach(element => {

				console.warn('缓存数据:' + element);
				if (element == null || element == undefined || element == '') {
					console.warn('无效缓存数据...');

				} else {

					var nowqueueArr = element.split('|');

					if (nowqueueArr[0] == queueItem.queueId) {

						if (nowqueueArr[2] == queueItem.totalAgentCount && nowqueueArr[3] == queueItem.busyAgentCount && nowqueueArr[4] == queueItem.idleAgentCount && nowqueueArr[5] == queueItem.queueWaitCount) {
							isFlag = 0;
						} else {
							isFlag = 1;
						}

						oQueueItemt = oQueueItemt + queueItem.queueId + '|' + queueItem.queueName + '|' + queueItem.totalAgentCount + '|' + queueItem.busyAgentCount + '|' + queueItem.idleAgentCount + '|' + queueItem.queueWaitCount + '&';

					} else {

						oQueueItemt = oQueueItemt + element + '&';
					}
				}

			});

			if (isFlag == -1) {
				oQueueItemt = oQueueItemt + queueItem.queueId + '|' + queueItem.queueName + '|' + queueItem.totalAgentCount + '|' + queueItem.busyAgentCount + '|' + queueItem.idleAgentCount + '|' + queueItem.queueWaitCount + '&';
			}

			oQueueItemt = oQueueItemt.substring(0, oQueueItemt.length - 1);

			console.log('队列消息数据：' + isFlag + ' 结果：' + oQueueItemt);

			var timestampN = Date.parse(new Date());

			if (isFlag != 0 && (timestampN - timestampO) / 1000 > 2) {

				this.oQueueItem = timestampN + '#' + oQueueItemt;
				console.log(this.oQueueItem);

				var queueData = encodeURIComponent(this.oQueueItem);

				var url = "/ngsapitask_pa/api/api7MoorQueue";
				console.warn('队列消息推送URL:' + url);

				var xhr = new XMLHttpRequest();
				xhr.open('POST', url, true);
				xhr.responseType = 'json';
				xhr.onload = function () {
					console.log('队列消息推送完成...');
				};
				xhr.onerror = function () {//请求错误
					console.warn('队列消息推送失败...');
				};

				xhr.send(queueData);

			} else {
				this.oQueueItem = timestampO + '#' + oQueueItemt;
				console.log('不满足推送消息条件');

			}
		} catch (error) {
			console.error(error);
		}

	},

	sendAction: function (json) {
		//hojo.byId("icallcenter.iframe").src="http://localhost:15062/?json=" + hojo.toJson(json) + "&random=" + Math.floor(Math.random()*100000);
	}

});